// MyThread.h: interface for the CMyThread class.
//
//
//////////////////////////////////////////////////////////////////////

#ifndef _MY_THREAD_H_
#define _MY_THREAD_H_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "windows.h"
#include "MySyncObjs.h"

const int TIME_WAITINGCLOSE	= 3000;		// 3000ms

class IThreadEvent  
{
public:
	virtual int		OnThreadCreate	(void)		= 0;		
	virtual int		OnThreadDestroy	(void)		= 0;
	
	virtual int		OnThreadWorkEvent	(void)	= 0;
	virtual int		OnThreadProcess		(void)	= 0;
};

class CMyThread  
{
public:
	CMyThread(IThreadEvent& event);
	virtual ~CMyThread();

public:
	enum { SUSPEND = true, RUN = false };
	BOOL	Create	(BOOL bSuspend=SUSPEND, DWORD dwWorkInterval=INFINITE);
	BOOL	Close	(void);

	void	Resume	(void);
	void	Suspend	(void);
	void	SetWorkEvent	(void)	{ ::SetEvent(m_hWorkEvent); }

	DWORD	GetWorkInterval() const	{ return m_dwWorkInterval; }
	void	SetWorkInterval(DWORD dwWorkInterval)	{ ::InterlockedExchange((LPLONG)&m_dwWorkInterval ,dwWorkInterval); }

	enum {	STATUS_INIT = 0, 
			STATUS_SUSPEND, 
			STATUS_RUNNING, 
			STATUS_CLOSING,
			STATUS_CLOSED };

	int		GetStatus(void) const { return m_nStatus; }

protected:
	DWORD		m_dwWorkInterval;
	IThreadEvent&	m_event;

private:
	BOOL		m_fTerminated;
	HANDLE		m_hThread;
	HANDLE		m_hExitEvent;
	HANDLE		m_hWorkEvent;

	DWORD			m_id;
	volatile int	m_nStatus;

	static DWORD WINAPI RunThread(LPVOID pThreadParameter);

public:
	static CMyThread*	CreateNew(IThreadEvent& refEvent, BOOL bSuspend = SUSPEND, DWORD dwWorkInterval = INFINITE);

private:
	void operator = (const CMyThread& /*opr*/)	{ return ; }
};

#endif // defined _MY_THREAD_H_
